package noncomunicating.classes;

import java.io.File;
import java.io.FileNotFoundException;

import util.Exception404;
import util.FileToBigException;
import util.IO;

import comunicating.classes.ServerLoop;

public class FileGetter extends abstracts.Step{
	private boolean fileFound;
	
	
	public FileGetter(Request request) {
		super(request);
		
		try {
			File theFile = IO.findFile(request.getFileString());
			fileFound = true;
			request.setStatusCode(200);
			request.setStatus("OK");
			try {
				request.setFileContent(IO.getFileBytes(theFile));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (FileToBigException e) {
				e.printStackTrace();
			}
			
		} catch (Exception404 e) {
			fileFound = false;
			request.setStatusCode(404);
			request.setStatus("Not Found");			
			request.setFileContent(ServerLoop.getNotFoundPage());
		}
		
	}


	@Override
	public void printOutput(boolean verbose) {
		System.out.println(this.getOutput(verbose));
		
	}


	@Override
	public String getOutput(boolean verbose) {
		String retString = null;
		if (verbose) {
			if (fileFound) {
				retString += request.getName() + ": File Found\n";
				retString += "Status: " + request.getStatus() + "\n";
				retString += "Code: " + request.getStatusCode() + "\n";
			} else {
				retString += request.getName() + ": File not Found. Using 404 page.\n";
				retString += "Status: " + request.getStatus() + "\n";
				retString += "Code: " + request.getStatusCode() + "\n";
			}
		}
		else{
			if (fileFound) {
				retString += "File Found.";
			}
			else {
				retString += "File not Found. Using 404 page.\n";
			}
		}
		return retString;
	}
}
